package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.DictionaryBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DictionaryMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.mysql.cj.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

/**
 * 添加分组信息
 * 
 * @author DaiSn
 * @version 创建时间：2018年12月19日 上午10:37:07
 */
public class DictionaryTypeAdd implements ServerInterface {

	private static Logger logger = LogManager.getLogger(DictionaryTypeAdd.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		DictionaryMapper mapper = factory.getMapper(DictionaryMapper.class);
		DictionaryBean bean = new DictionaryBean();
		try {
			bean = JsonUtils.objectToPojo(req.getData(), DictionaryBean.class);
		} catch (Exception e) {
			logger.error("非法参数", e);
			factory.close(false);
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
		if (StringUtils.isNullOrEmpty(bean.getCode()) || StringUtils.isNullOrEmpty(bean.getName())) {
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
		bean.setId(new ObjectId().toHexString());
		bean.setCreateBy(userInfo.getUserInfo().getName());
		bean.setCreateTime(CommonUtils.getCurrentTime());
		if (mapper.findDictionaryCount(bean) != 0) {
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "已存在相同的组信息", void.class);
		} else {
			bean.setSort(mapper.findDictionaryMaxSort()+1);
			mapper.addDictionaryType(bean);
		}
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
	}

}
